import os

from django import http
from django.conf import settings
from django.shortcuts import render
from django.views import View

from apps.orders.models import OrderInfo
from alipay import AliPay

from apps.payment.models import Payment
from utils.response_code import RETCODE
# 保存订单实现成功界面
class PayMentStatusView(View):
    def get(self, request):
        # 1.接收 解析sign
        query_dict = request.GET
        data = query_dict.dict()
        signature = data.pop('sign')

        # 2. 支付宝校验
        # 2.1 支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 2.2 verify校验
        success = alipay.verify(data, signature)
        if success:

            # 3. 取出参数 存入数据库
            order_id = data.get('out_trade_no')
            trade_no = data.get('trade_no')

            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_no
            )

            # 4. 修改订单状态
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])

            context = {
                'trade_id': trade_no
            }

            return render(request, 'pay_success.html', context)
        else:

            return http.HttpResponseForbidden('非法请求')

#首页  获取支付宝的
class PayMentView(View):
    def get(self, request, order_id):
        #  *   1.接收参数 order_id
        # *   2. 验证订单是否存在
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            return http.HttpResponseBadRequest('订单不存在!')

        # *   3. 验证支付宝的对象--创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # *   4. 加密 order_id,subject,total_amount 参数 支付宝
        order_string = alipay.api_alipay_trade_page_pay(
            subject="美多商城:{}".format(order_id),
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL

        )
        # *   5. 返回支付宝的的登录网址--拼接网址---网关  + 加密完strig
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})
